//
//  NQBarGraph.m
//  NQBarGraphExample
//
//  Created by AhmedElnaqah on 6/2/13.
//  Copyright (c) 2013 elnaqah. All rights reserved.
//
//The MIT License (MIT)
//
//Copyright (c) 2013 ahmed elnaqah
//
//Permission is hereby granted, free of charge, to any person obtaining a copy
//of this software and associated documentation files (the "Software"), to deal
//in the Software without restriction, including without limitation the rights
//to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
//copies of the Software, and to permit persons to whom the Software is
//furnished to do so, subject to the following conditions:
//
//The above copyright notice and this permission notice shall be included in
//all copies or substantial portions of the Software.
//
//THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
//IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
//FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
//AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
//LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
//OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
//THE SOFTWARE.


#import "NQBarGraph.h"
#import "NQData.h"
#import <QuartzCore/QuartzCore.h>
#import "IWRGB.h"
#define BAR_WIDTH_MAX 100
#define BAR_WIDTH_MIN 3
#define BAR_WIDTH_DEFAULT 15  //柱子的宽度
#define BAR_SPACES_DEFAULT 5
#define HORIZONTAL_PADDING 25 //水平间距
#define VERTICAL_PADDING 30  //竖直间距
#define HORIZONTAL_START_LINE 0.2 //水平虚线条
#define VERTICAL_START_LINE 0.2 //竖直虚线条
#define VERTICALE_DATA_SPACES 20//左侧竖直数字的间距
#define LABEL_DIM 20

/**
 *  颜色
 */
#define RGB(r, g, b)        [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:1.0]
#define RGBA(r, g, b, a)    [UIColor colorWithRed:r/255.0 green:g/255.0 blue:b/255.0 alpha:a]

@interface NQBarGraph()
@property CGPoint contentScroll;
@property int maxHeight;
@property int maxWidth;
@property(nonatomic,weak)NSString*text;

@property (nonatomic) int yValueMax;
@property(nonatomic,assign)CGRect head;
@property(nonatomic,weak)UILabel*popLable;

@end
@implementation NQBarGraph


-(NSMutableArray*)mut{
    if (_mut==nil) {
        _mut=[NSMutableArray array];
    }
    return _mut;
}

-(NSMutableArray*)btnArray{
    
    if (_btnArray==nil) {
        _btnArray=[NSMutableArray array];
    }
    return _btnArray;
}

-(NSMutableArray*)lableArray{
    
    if (_lableArray==nil) {
        
        _lableArray=[NSMutableArray array];
    }
    return _lableArray;
}


- (id)initWithFrame:(CGRect)frame
{
    self = [super initWithFrame:frame];
    if (self) {
        // Initialization code
        self.barWidth=BAR_WIDTH_DEFAULT;//柱子的宽度
        self.spaceBetweenBars=BAR_SPACES_DEFAULT;//各个柱子间的间距
//        self.backgroundColor=[UIColor colorWithWhite:0.8 alpha:0.5];//背景色
        self.backgroundColor=[UIColor clearColor];
        self.linesColor=[UIColor colorWithRed:94.0/255.0 green:148.0/255.0 blue:206.0/255.0 alpha:1.0];//黑色虚线条的颜色
        self.numbersColor=[UIColor colorWithRed:0.4 green:0.4 blue:0.8 alpha:0.3];//左侧竖直阿拉伯lable的颜色

        self.numbersTextColor=[UIColor colorWithRed:0.3 green:0.9 blue:0.3 alpha:0.5];//左侧竖直阿拉伯lable文本的颜色

        self.dateColor=[UIColor blackColor];//底部Day,Month的颜色
        self.bottomDateColor=[UIColor blackColor];
        self.contentScroll=CGPointZero;
//        self.layer.cornerRadius=20;//设置四个圆角
//        self.layer.masksToBounds=YES;
//        self.barColor=[UIColor colorWithRed:0.5 green:0.6 blue:0.5 alpha:1];//各个柱子的颜色
        self.textColor=[UIColor redColor];//左侧tasks和底部date的文本颜色
        self.dottedLineColor=[UIColor clearColor];//内部虚线的颜色
        self.barOuterLine=[UIColor clearColor];//各个柱子四周边缘的颜色
        self.fontName=@"Helvetica";
        self.dateFontSize=8;//底部date的字体
        self.titlesFontSize=20;//左侧task的字体
        

    }
    return self;
}

-(void)setFrame:(CGRect)frame
{
    [super setFrame:frame];
    [self setNeedsDisplay];
}
// Only override drawRect: if you perform custom drawing.
// An empty implementation adversely affects performance during animation.

-(void)setYlables:(NSArray *)ylables{
    
    _ylables=ylables;
    
}

-(void)setTTag:(NSInteger)TTag{
    
    _TTag=TTag;
}

- (void)drawRect:(CGRect)rect
{
    // Drawing code
    float minOfTwo=MIN(self.bounds.size.width, self.bounds.size.height);
    
//    NSLog(@"%f",self.bounds.size.height);
    
    CGContextRef context=UIGraphicsGetCurrentContext();//开启上下文
    CGContextTranslateCTM(context, 0.0f, self.bounds.size.height);
    CGContextScaleCTM(context, 1, -1);
    
    
    CGFloat dashPattern[]= {6.0, 5};
    CGContextSetLineWidth(context, 1.0);//设置内部虚线和柱子边缘的线宽
    CGContextSetLineDash(context, 0.0, dashPattern, 2);//设置内部虚线和柱子边缘的图样
    
    
    CGContextSelectFont (context,[self.fontName UTF8String],self.dateFontSize,kCGEncodingMacRoman);
    //CGContextSetCharacterSpacing (context, 5);
    CGContextSetTextDrawingMode (context, kCGTextFill);//设置填充模式
    
    
    [self.dateColor set];
    //把Day和Month显示在对应位置
//    CGContextShowTextAtPoint (context, (HORIZONTAL_START_LINE*minOfTwo)-35, VERTICAL_START_LINE*minOfTwo -15, [@"day" UTF8String], 3);
//    CGContextShowTextAtPoint (context, (HORIZONTAL_START_LINE*minOfTwo)-35, VERTICAL_START_LINE*minOfTwo -30, [@"month" UTF8String], 5);

    
    
    //write tasks and date,左侧的tasks和底部的date
    CGContextSelectFont (context,[self.fontName UTF8String],20,kCGEncodingMacRoman);
    CGContextSetTextDrawingMode (context, kCGTextFill);
    [self.textColor set];
    CGContextShowTextAtPoint(context, self.bounds.size.width/2-35, 10, [self.datesBarText UTF8String], 4);
    
    CGContextSetTextMatrix(context, CGAffineTransformMakeRotation(90*M_PI/180));
    CGContextShowTextAtPoint(context, self.titlesFontSize, self.bounds.size.height/2-35, [self.tasksBarText UTF8String], 5);
    
    
    
    CGContextSetTextMatrix(context, CGAffineTransformIdentity);
    CGContextSelectFont (context,[self.fontName UTF8String],self.dateFontSize,kCGEncodingMacRoman);
    
    
    
    NSInteger max=0;
    for (NSString * valueString in _ylables) {
        NSInteger value = [valueString integerValue];
        
        if (value > max) {
            max = value;
        }
        
    }
    //Min value for Y label
    if (max < 5) {
        max = 5;
    }
    
    
    
    _yValueMax=(int)max;//左侧y轴最大的值
    self.yValueMax=(int)max;
    float level = max /5.0;//最大的数字除以5,左侧数字lable之间的间距
    for (int i=0; i<=6; i++) {
        int height=VERTICALE_DATA_SPACES* i;
        float verticalLine=height+VERTICAL_START_LINE*minOfTwo-self.contentScroll.y;
        if (verticalLine>VERTICAL_START_LINE*minOfTwo) {
            
            NSString * numberString=[NSString stringWithFormat:@"%1.f",(i-1)*level];//设置左侧竖直数字
            
            UILabel*lable=[[UILabel alloc]init];
            
            [lable setTextColor:[UIColor whiteColor]];
            
            CGFloat chartCavanHeight=self.frame.size.height;
            
            lable.frame=CGRectMake(10,chartCavanHeight-i*25-30, 30, 15);//左侧lable的自身高度为15
            [lable setTextAlignment:NSTextAlignmentCenter];
            
            [lable setFont:[UIFont systemFontOfSize:12]];
            
//            lable.backgroundColor=[UIColor redColor];
            
            [lable setText:numberString];
            
//            [self addSubview:lable];
            
        }
    }
    

    //开始画柱状图和设置柱状图的颜色
    NSMutableArray*mut=[NSMutableArray array];
    
    
    for (int i=0; i<_ylables.count; i++) {
        
        NSString*string=_ylables[i];
        
        float grade=[string floatValue]/_yValueMax;
        
        CGFloat barheigth = grade*40;//高度可以随着所乘是数字调整
        
        if (VERTICAL_START_LINE*minOfTwo-self.contentScroll.y <VERTICAL_START_LINE*minOfTwo) {
            barheigth-=self.contentScroll.y;
        }
        float xPosition=HORIZONTAL_START_LINE*minOfTwo+(i+1)* self.spaceBetweenBars + i * self.barWidth+self.contentScroll.x;//x的位置

        
        if (xPosition>=HORIZONTAL_START_LINE*minOfTwo && xPosition<self.bounds.size.width ){
            [self.dateColor set];
            
            //画柱状图
            if (xPosition>=HORIZONTAL_START_LINE*minOfTwo && xPosition<self.bounds.size.width ) {
                CGRect barRect=CGRectMake(xPosition, VERTICAL_START_LINE*minOfTwo, self.barWidth, barheigth);//柱状图的尺寸
                
                [self.barOuterLine set];//柱状图边缘的颜色
                CGContextStrokeRect(context, barRect);//画柱状图
                
                self.rect=barRect;
                
                NSValue *value=[NSValue valueWithCGRect:barRect];
                
                [mut addObject:value];
                
                self.mut=mut;
                
                //在这里做一次判断，判断传递进来的数据是AQI还是PM10等其他以显示对应的颜色
                
                if (_TTag==0) {
                    
                    self.barColor=[IWRGB RGBWithAQI:string];
                    
                    [self.barColor set];//柱状图的颜色

                    UIRectFill(barRect);
                }else if (_TTag==1){
                    
                    self.barColor=[IWRGB RGBWithPM2_5:string];
                    
                    [self.barColor set];//柱状图的颜色
                    
                    UIRectFill(barRect);
                    
                }else if (_TTag==2){
                    
                    self.barColor=[IWRGB RGBWithPM10:string];
                    
                    [self.barColor set];//柱状图的颜色
                    
                    UIRectFill(barRect);

                    
                }else if (_TTag==3){
                    
                    
                    self.barColor=[IWRGB RGBWithO3:string];
                    
                    [self.barColor set];//柱状图的颜色
                    
                    UIRectFill(barRect);
                    
                    
                }else if (_TTag==4){
                    self.barColor=[IWRGB RGBWithSO2:string];
                    
                    [self.barColor set];//柱状图的颜色
                    
                    UIRectFill(barRect);
                    
                }else if (_TTag==5){
                    
                    self.barColor=[IWRGB RGBWithNO2:string];
                    
                    [self.barColor set];//柱状图的颜色
                    
                    UIRectFill(barRect);
                }else if (_TTag==6){
                    
                    self.barColor=[IWRGB RGBWithCO:string];

                    
                    [self.barColor set];//柱状图的颜色
                    
                    UIRectFill(barRect);
                }

            } else if(xPosition+self.barWidth >HORIZONTAL_START_LINE*minOfTwo  && xPosition<HORIZONTAL_START_LINE*minOfTwo )
            {
                
                [self.barColor set];
                UIRectFill(CGRectMake(HORIZONTAL_START_LINE*minOfTwo, VERTICAL_START_LINE*minOfTwo, self.barWidth-(HORIZONTAL_START_LINE*minOfTwo-xPosition), barheigth));

            }
 
        }
        //主要是设置底部的时间数据 每三段显示一次
        int index=0;
        for (NSString * dataObject in self.dataSource) {
            
//
           NSString *timeStr = [dataObject stringByReplacingCharactersInRange:NSMakeRange(0, 10) withString:@""];
            
//            NSLog(@"dataObject:%@", timeStr);
            
            float xPosition=HORIZONTAL_START_LINE*minOfTwo+(index+1)* self.spaceBetweenBars + index * self.barWidth+self.contentScroll.x;//x的位置
            
            if (xPosition>=HORIZONTAL_START_LINE*minOfTwo && xPosition<self.bounds.size.width ){
                [self.bottomDateColor set];


                if (index%3==0) {
                    
                //显示底部的日，月数据
                CGContextShowTextAtPoint (context, xPosition+self.barWidth/2-2-9, VERTICAL_START_LINE*minOfTwo - 15, [timeStr UTF8String], 6);
                }
            }
            
            index++;
 
        }
        
        
    }

//    // draw axes,画外部黑色虚线
    CGContextSetLineWidth(context, 1);
    CGContextMoveToPoint(context, HORIZONTAL_START_LINE*minOfTwo, VERTICAL_START_LINE*minOfTwo);
    [self.linesColor set];

//    CGContextAddLineToPoint(context, HORIZONTAL_START_LINE*minOfTwo, self.bounds.size.height);
//    CGContextStrokePath(context);
//
    CGContextMoveToPoint(context, HORIZONTAL_START_LINE*minOfTwo, VERTICAL_START_LINE*minOfTwo);
    CGContextAddLineToPoint(context, self.bounds.size.width, VERTICAL_START_LINE*minOfTwo);
    CGContextStrokePath(context);
    
    
    
}


#pragma mark setDataSource

/*
 拿到外界传进的数据,设置底部日期
 */

-(void)setDataSource:(NSArray *)dataSource
{
    _dataSource=dataSource;
    
    //calculate the limit of height,计算纵坐标的最大高度
    //    _maxHeight=0;
    //    for (NQData * dataObject in _dataSource) {
    //        int height=VERTICALE_DATA_SPACES* [dataObject.number intValue];
    //        _maxHeight=MAX(height, _maxHeight);
    //    }
    //    _maxHeight-=self.spaceBetweenBars;
    //calculate the limit of width,计算横坐标的最大宽度
    _maxWidth=([_dataSource count]-1)*(self.barWidth+self.spaceBetweenBars);
    
//    [self touchesMoved:[NSSet set] withEvent:nil];
    [self setNeedsDisplay];
}



#pragma mark touch handling
-(void)touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event
{


    [self.btn removeFromSuperview];
    
    CGPoint touchLocation = [[touches anyObject] locationInView:self];//当前点

//    NSLog(@"self.mut:%@", self.mut);
    NSMutableArray *temp = [NSMutableArray array];
    for (NSString * dataObject in self.dataSource){
        [temp addObject:dataObject];
    }
    int i = 0;
    for (NSValue*value in self.mut) {
        
//        NSLog(@"value%@", value);
        CGRect rect=[value CGRectValue];
        
        if (touchLocation.x>=rect.origin.x&&touchLocation.x<=rect.origin.x+rect.size.width) {

             CGFloat a= rect.size.height/30*self.yValueMax;
            
            NSString*str=[NSString stringWithFormat:@"%@\n%.fug/m³",temp[i],a];
            i++;
            
//            UIView *outView = [[UIView alloc]init];
//            outView.center = CGPointMake(rect.origin.x+rect.size.width*0.5,  self.frame.size.height-rect.size.height-20);
//            outView.bounds = CGRectMake(0, 0, 100, 30);
//            outView.backgroundColor = [UIColor whiteColor];
//            outView.layer.borderWidth = 0.1;
//            outView.layer.borderColor = RGB(48, 134, 247).CGColor;
//            outView.layer.masksToBounds = YES;
//            outView.layer.cornerRadius = 5;
//            
//            [self addSubview:outView];
//            _outView = outView;
//            UILabel *valueLable = [[UILabel alloc]init];

            UIButton*btn=[[UIButton alloc]init];
            [btn addTarget:self action:@selector(btnClick) forControlEvents:UIControlEventTouchUpInside];
            btn.center=CGPointMake(rect.origin.x+rect.size.width*0.5,  self.frame.size.height-rect.size.height-30);
            btn.bounds=CGRectMake(0,0, 100, 50);
            btn.layer.borderWidth = 0.5;
            btn.layer.borderColor = RGB(48, 134, 247).CGColor;
            btn.layer.cornerRadius = 10;
            btn.titleLabel.textAlignment=NSTextAlignmentCenter;
            btn.titleLabel.numberOfLines = 0;
            btn.titleLabel.font=[UIFont systemFontOfSize:12];
            [btn setTitleColor:[UIColor blackColor] forState:UIControlStateNormal];
            [btn setTitle:str forState:UIControlStateNormal];
            btn.backgroundColor = [UIColor whiteColor];
            
            
            [self addSubview:btn];
        
            [self.btnArray addObject:btn];
            
            self.btn=btn;
        }
    }
   
}

-(void)btnClick{
    
    [self.btn removeFromSuperview];
    
}

/*
 上下左右滚动柱状图
 */

-(void)touchesMoved:(NSSet *)touches withEvent:(UIEvent *)event
{
    
    CGPoint touchLocation=[[touches anyObject] locationInView:self];//当前点
    CGPoint prevouseLocation=[[touches anyObject] previousLocationInView:self];//先前点
    float xDiffrance=touchLocation.x-prevouseLocation.x;
    
//    NSLog(@"当前%@-先前%@", touchLocation, prevouseLocation); 
    
    _contentScroll.x+=xDiffrance;
    
    if (_contentScroll.x >0) {
        _contentScroll.x=0;
    }
    
    
    if (-_contentScroll.x>self.maxWidth) {
        _contentScroll.x=-self.maxWidth;
    }
    
//    for (UIButton*btn in self.btnArray) {
//        
//        btn.userInteractionEnabled = NO;
//        [btn removeFromSuperview];
//        
//    }

    for (UILabel*lable in self.lableArray) {
        
        [lable removeFromSuperview];
    }
    
    [self setNeedsDisplay];
}

-(void)touchesCancelled:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}
-(void)touchesEnded:(NSSet *)touches withEvent:(UIEvent *)event
{
    
}


@end
